from PySide6.QtWidgets import QApplication , QMainWindow , QPushButton
class Mywindow(QMainWindow):
def __init__(self):
super().__init__()
#創建並設置按鈕
btn = QPushButton("按鈕",self)
btn.setGeometry(0,0,100,100)
#觸發
btn.clicked.connect(self.print)
#槽函數:print
def print(self):
print("按鈕被點擊了")
if __name__ == "__main__":
app = QApplication([])
window = Mywindow()
window.show()
app.exec()
btn.clicked.connect(self.print)
:這行程式碼將按鈕的 clicked 訊號與 print 槽連接起來,當按鈕被點擊時,訊號會觸發 print 函數,顯示按鈕被點擊了。from PySide6.QtWidgets import QApplication , QMainWindow , QLineEdit , QLabel
class Mywindow(QMainWindow):
def __init__(self):
super().__init__()
#創建和設置元件
self.LineEdit = QLineEdit(self)
self.LineEdit.setGeometry(0,0,100,100)
self.Label = QLabel("label",self)
self.Label.setGeometry(100,0,100,100)
#改變LineEdit輸入時,會發出信號
self.LineEdit.textChanged.connect(self.changeLabel)
#槽函數:changeLabel
def changeLabel(self):
self.Label.setText(self.LineEdit.text())
if __name__ == "__main__":
app = QApplication([])
window = Mywindow()
window.show()
app.exec()
self.LineEdit.textChanged.connect(self.changeLabel)
: 當輸入改變時會發出信號,觸發changeLabel改變Qlabel。#self.LineEdit.text()
: 獲取LineEdit目前的文字 。QLineEdit
也可以使用 returnPressed
信號,當用戶按下 Enter 鍵時觸發。